package com.diors.commons.network.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.diors.commons.log.DiorsLogger;
import com.diors.commons.network.DispatcherHandler;

/**
 * 网络服务器端服务器
 * @author	darren.ouyang
 * @data	2013-9-9
 */
public class DiorsServer extends AbstractServer
{
	
	private static final DiorsLogger log = DiorsLogger.getLogger(DiorsServer.class);
	
	public DiorsServer(DispatcherHandler dispatcher, int port) 
	{
		super(dispatcher, new InetSocketAddress(port));
	}
	
	public DiorsServer(DispatcherHandler dispatcher, String hostname, int port) 
	{
		super(dispatcher, new InetSocketAddress(hostname, port));
	}
	
	/**
	 * 服务器连接方法
	 * @create	2013-9-9	darren.ouyang
	 */
	public void open ()
	{
		ChannelFactory factory = new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
		ServerBootstrap bootstrap = new ServerBootstrap(factory);
		
		/* 为每个连接设置成相同的Handler对象 */
		ChannelPipeline pipline = bootstrap.getPipeline();
		pipline.addLast("handler", dispatcher);

		/* 设置socket选项 */
		/* child意味配置项适用我们接收到的通道实例,而不是ServerSocketChannel实例 */
		bootstrap.setOption("child.tcpNoDelay", true);  	// 提高数据的实时响应性,数据不延迟
	    bootstrap.setOption("child.keepAlive", true);  		// ack探测包 是否继续维持该socket
		
	    /* 返回了一个绑定了本地地址的服务端Channel通道对象,并注册到管道集合中 */
		bootstrap.bind(address);
		
		log.info(new StringBuilder("服务器启动监听IP[").append(address.getHostString()).
				append("]端口[").append(address.getPort()).append("]").toString());
	}

	/**
	 * 服务器关闭方法
	 * @create	2013-9-9	darren.ouyang
	 */
	public void close ()
	{
		
	}
}
